package com.andrew.demo.dao;

import com.andrew.demo.mapper.BaseMapper;
import com.andrew.demo.mapper.MapperHelper;
import com.andrew.demo.mapper.StudentMapper;
import com.andrew.demo.model.BaseDbEntity;
import com.andrew.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcDaoSupport;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.lang.reflect.ParameterizedType;
import java.util.List;

@Repository
@Transactional
public abstract class BaseDaoImpl<T extends BaseDbEntity> extends NamedParameterJdbcDaoSupport implements BaseDao<T> {

    /**
     * 具体操作的实体类对象
     */
    private Class<T> entityClass;

    /**
     * 具体操作的实体类对象
     */
    private BaseMapper rowMapper;

    @Autowired
    public BaseDaoImpl(DataSource dataSource) throws IllegalAccessException, InstantiationException, ClassNotFoundException {
        this.setDataSource(dataSource);
        entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        rowMapper = MapperHelper.getRowMapperByClass(entityClass.getSimpleName());
    }

    @Override
    public List<T> QueryList() throws ClassNotFoundException, InstantiationException, IllegalAccessException {
        System.out.println(entityClass.getName() + "：查询所有方法");

        String className="User";
        //加载一个用户实体类UserBean
        //Class mapperCls = Class.forName("com.andrew.demo.mapper."+className+"Mapper");

        String sql = StudentMapper.SELECT_SQL;
        List<T> list = this.getJdbcTemplate().query(sql, rowMapper);
        return list;
    }

}
